package mall.demo.crawl;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import mall.demo.mybatis.pojo.Product;
import mall.demo.util.CrawlType;

public class JdSearchCrawler implements ICrawler{
	private static String jdPrefix = "https://search.jd.com/Search?";
	private static Logger logger = LoggerFactory.getLogger(JdSearchCrawler.class);
	
	private String keyword;
	public JdSearchCrawler(String keyword) {
		// TODO Auto-generated constructor stub
		this.keyword = keyword;
	}

//	@Override
	public void setProperties(Properties prop) {
		// TODO Auto-generated method stub
		
	}

//	@Override
	public List<Product> crawl() {
		if (this.keyword == null || this.keyword.trim().equals("")) {
			return new ArrayList<Product>();
		}
		List<Product> list = new ArrayList<Product>();
		String url = jdPrefix + "keyword=" + keyword + "&enc=utf-8";
		url += "&wq=" + keyword;
		try {
			Document doc = Jsoup.connect(url).get();
			Elements elements = doc.select("#J_goodsList ul li.gl-item");
			Iterator<Element> it = elements.iterator();
			while(it.hasNext()) {
				try {
					Element element = it.next();
					String name = element.select("div.p-name").text();
					String link = element.select("div.p-name a").attr("href");
					String price = element.select("div.p-price strong").attr("data-price");
					String code = CrawlType.getProductCodeByType(CrawlType.JDSEARCH);
					Product p = new Product();
					p.setCode(code);
					p.setName(name);
					p.setDescription(name + " 来自 " + CrawlType.JDSEARCH + " 可见" + link);
					p.setPrice(Double.parseDouble(price));
					list.add(p);	
				} catch(Exception e) {
					logger.error(e.getMessage(), e);
				}
			}
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}
		return list;
	}

}
